package net.zjitc.demosecurity6.service.impl;


import com.alibaba.fastjson.JSON;
import net.zjitc.demosecurity6.pojo.LoginUser;
import net.zjitc.demosecurity6.pojo.User;
import net.zjitc.demosecurity6.service.UserService;
import net.zjitc.demosecurity6.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

/**
 * @Author zhao
 * @DATE 2025/4/25 15:11
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Override
    public String login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken= new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword());
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        if (authentication==null){
            throw new RuntimeException("登录失败");
        }

        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        //loginuser--->string
        String jsonString = JSON.toJSONString(loginUser);
        //jwt 生成token
        String jwt = JwtUtil.generateToken(jsonString, 1000 * 60 * 60 * 24);
        return jwt;
    }
}
